package com.lebang.controller.api.donwn;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.common.Require;
import com.lebang.common.ValidCode;
import com.lebang.component.RedisClient;
import com.lebang.domain.*;
import com.lebang.entity.RequestHeaders;
import com.lebang.model.Whether;
import com.lebang.model.enums.buss.DownStatus;
import com.lebang.model.enums.buss.RewardTypeUscan;
import com.lebang.service.*;
import com.lebang.service.earn.DownMemberCountConfigService;
import com.lebang.service.sys.AppLookRecordService;
import com.lebang.service.sys.DictService;
import com.lebang.service.sys.DownFailConfigService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: hwq
 * @Date: 2020/3/13 15:53
 * @Version 1.0
 */
@RestController
@RequestMapping("/appv2/download")
public class DownapiV2 {
    @Autowired
    private AppEarnRouseSortService appEarnRouseSortService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private CpaService cpaService;
    @Autowired
    private NewRouseService newRouseService;
    @Autowired
    private MemberNewTaskService memberNewTaskService;
    @Autowired
    private TaskRouseClickService taskRouseClickService;
    @Autowired
    private TaskRouseDetailService taskRouseDetailService;
    @Autowired
    private AppLookRecordService appLookRecordService;
    @Autowired
    private DownMemberCountConfigService downMemberCountConfigService;
    @Autowired
    private DownFailConfigService downFailConfigService;
    @Autowired
    private DictService dictService;
    @Autowired
    private DownloadMemberRecordService downloadMemberRecordService;




    @Sessionid
    @Require
    @PostMapping("/update/key")
    public JsonData update(HttpServletRequest request, String key, Long recordId) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        if (downAppService.selectByKey(key) == null) {
            return Callback.fail("success", "key不存在");
        }

        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("2001", "任务不存在");
        }
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("2002", "任务不存在");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("2003", "任务不存在");
        }
        if (cpaService.getZyData().equals(record.getSdkKey())) {
            return Callback.fail("2004", "任务错误");
        }
        record.setSdkKey(key);
        downAppService.updateKey(record);
        return Callback.success("success", "修改成功");
    }

    @Sessionid
    @Require
    @PostMapping("/sortlist")
    public JsonData list(HttpServletRequest request) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        List<String> strings = this.getSortList(requestHeaders);
        return Callback.success("success", "查询成功", strings);

    }

    @Sessionid
    @Require
    @GetMapping("/clcik/{id}")
    public JsonData clciklist(HttpServletRequest request, @PathVariable("id") Long clickId) {
        MemberClickRouse rouses = downAppService.findClickByClickId(clickId);
        if (rouses == null) {
            return Callback.fail("201", "签到不存在..");
        }
        LocalDate now = LocalDate.now();
        if (rouses.getRouseDetailId() == null) {
            List<TaskRouseClick> rouseClicks = taskRouseClickService.findListByRouseId(rouses.getRouseId());
            long days = taskRouseClickService.getMaxDay(rouseClicks, rouses.getRouseId());
            if (downAppService.checkClickByMemberId(rouses.getMemberId(),
                    rouses.getId(),
                    rouses.getCreateTime().toLocalDate().plusDays(days))
                    || taskRouseClickService.checkLast(rouses, days)) {
                return Callback.fail("200", "你已经全部签到完成了");
            } else {
                rouseClicks = taskRouseClickService.filterList(rouseClicks, rouses, now);
                return Callback.success("201", "查询成功", rouseClicks);
            }
        } else {
            List<ClickStrategyDetail> clickStrategyDetails = taskRouseDetailService.selectByStrategyId(rouses.getStrategyId());
            long days = taskRouseClickService.getMaxDay(clickStrategyDetails);
            if (downAppService.checkClickByMemberId(rouses.getMemberId(),
                    rouses.getId(),
                    rouses.getCreateTime().toLocalDate().plusDays(days))
                    || taskRouseClickService.checkLast(rouses, days)) {
                return Callback.fail("200", "你已经全部签到完成了");
            } else {
                clickStrategyDetails = taskRouseDetailService.filterList(clickStrategyDetails, rouses, now);
                return Callback.success("201", "查询成功", clickStrategyDetails);
            }
        }
    }

    @ValidCode
    @Sessionid
    @Require
    @GetMapping("/clcikv2")
    public JsonData clciklistv2(HttpServletRequest request, Long id) {
        JSONObject jsonObject = new JSONObject();
        if (id == null) {
            return Callback.fail("200", "参数非法");
        }
        MemberClickRouse rouses = downAppService.findClickByClickId(id);
        if (rouses == null) {
            return Callback.fail("201", "签到不存在..");
        }
        TaskRouse rouse1 = newRouseService.selectById(rouses.getRouseId());
        jsonObject.put("open_return", rouse1.getOpenReturn());
        LocalDate now = LocalDate.now();
        if (rouses.getRouseDetailId() == null) {
            List<TaskRouseClick> rouseClicks = taskRouseClickService.findListByRouseId(rouses.getRouseId());
            long days = taskRouseClickService.getMaxDay(rouseClicks, rouses.getRouseId());
            if (downAppService.checkClickByMemberId(rouses.getMemberId(),
                    rouses.getId(),
                    rouses.getCreateTime().toLocalDate().plusDays(days))
                    || taskRouseClickService.checkLast(rouses, days)) {
                return Callback.fail("200", "你已经全部签到完成了");
            } else {
                rouseClicks = taskRouseClickService.filterList(rouseClicks, rouses, now);
                jsonObject.put("data", rouseClicks);
            }
        } else {
            List<ClickStrategyDetail> clickStrategyDetails = taskRouseDetailService.selectByStrategyId(rouses.getStrategyId());
            long days = taskRouseClickService.getMaxDay(clickStrategyDetails);
            if (downAppService.checkClickByMemberId(rouses.getMemberId(),
                    rouses.getId(),
                    rouses.getCreateTime().toLocalDate().plusDays(days))
                    || taskRouseClickService.checkLast(rouses, days)) {
                return Callback.fail("200", "你已经全部签到完成了");
            } else {
                clickStrategyDetails = taskRouseDetailService.filterList(clickStrategyDetails, rouses, now);
                jsonObject.put("data", clickStrategyDetails);
            }
        }
        return Callback.success("201", "查询成功", jsonObject);
    }

    @Sessionid
    @PostMapping("/upload/check")
    public JsonData upload(HttpServletRequest request
            , @RequestParam String sdkKey,
                           @RequestParam String title,
                           @RequestParam String subTitle,
                           @RequestParam String jumpUrl,
                           @RequestParam String unineKey) {
        AppLookRecord record = new AppLookRecord();
        record.setHasDeleted(0);
        record.setCreateTime(LocalDateTime.now());
        record.setModifyTime(LocalDateTime.now());
        record.setEnable(0);
        record.setTitle(title);
        record.setSubTitle(subTitle);
        record.setJumpUrl(jumpUrl);
        record.setUnineKey(unineKey);
        record.setSdkKey(sdkKey);
        boolean check = appLookRecordService.check(record);
        return Callback.success("success", "成功", check);
    }

    public static void main(String[] args) {
        LocalDate star = LocalDate.of(2020, 3, 9);
        LocalDate end = LocalDate.of(2020, 6, 1);
        System.out.println(star.until(end, ChronoUnit.DAYS));

    }

    @PostMapping("/dddmmmddd")
    public JsonData ddd(HttpServletRequest request) {
        LocalDate star = LocalDate.of(2020, 3, 9);
        for (int i = 0; i <= 90; i++) {
            for (int k = 0; k < 24; k++) {
                if (k < 10) {
                    System.out.println("CSJ_RECORD_COUNT:" + star.format(DateTimeFormatter.ISO_DATE) + "-0" + k);
                    redisClient.delOne("CSJ_RECORD_COUNT:" + star.format(DateTimeFormatter.ISO_DATE) + "-0" + k);
                } else {
                    System.out.println("CSJ_RECORD_COUNT:" + star.format(DateTimeFormatter.ISO_DATE) + "-" + k);
                    redisClient.delOne("CSJ_RECORD_COUNT:" + star.format(DateTimeFormatter.ISO_DATE) + "-" + k);
                }

            }
            star = star.plusDays(1);
        }

//        LocalDate end = LocalDate.of(2020, 6, 1);
//          System.out.println(star.until(end, ChronoUnit.DAYS));

        return Callback.success("success", "查询成功", null);
    }

    public List<String> getSortList(RequestHeaders headers) {
        List<String> strings = new ArrayList<>();
        Optional<String> sortList = Optional.ofNullable(redisClient.hget("down_sortlist", headers.getAppStore()));
        if (sortList.isPresent()) {
            strings = JSON.parseArray(sortList.get(), String.class);
        } else {
            List<TaskRouse> rouses = newRouseService.selectAllByEnable(headers);
            for (TaskRouse next : rouses) {
                if (!cpaService.getZyData().equals(next.getSdkKey())) {
                    strings.add(next.getSdkKey());
                }
            }
            redisClient.hset("down_sortlist", headers.getAppStore(), JSON.toJSONString(strings));
        }
        return strings;
    }

    public JsonData zyCheck(RequestHeaders header) {
        JSONObject jsonObject = new JSONObject();
        TaskRouseDetail detail = cpaService.getDetailByZy(header.getUserid(), header);
        if (detail == null) {
            return Callback.fail("207", "今日暂无任务，请明日再来");
        }
        DownloadMemberRecord record = cpaService.pull(header.getUserid(), header, detail);
        jsonObject.put("open_return", 1);
        jsonObject.put("type", 1);
        jsonObject.put("recordId", record.getId());
        jsonObject.put("time", record.getTime());
        jsonObject.put("sdk_key", record.getSdkKey());
        jsonObject.put("count", downAppService.getCountV2(header.getUserid(), header.getAppStore()));
        jsonObject.put("detail", detail);
        return Callback.success("success", "查询成功", jsonObject);
    }

    ;

    @PostMapping("/zy/init")
    public JsonData zy(HttpServletRequest request, String pkgName) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        if (TextUtil.isEmpty(pkgName)) {
            return Callback.success("success", "查询成功");
        }
        Integer i = downloadMemberRecordService.checkPkgName(pkgName, requestHeaders.getUserid());
        if (i != null) {
            return Callback.success("success", "查询成功");
        }
        DownloadMemberRecord record = new DownloadMemberRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setModifyTime(LocalDateTime.now());
        record.setHasDeleted(0);
        record.setPkgName(pkgName);
        record.setAppName("");
        record.setType(1);
        record.setCategory(1);
        record.setMoney(0);
        record.setMemberId(requestHeaders.getUserid());
        record.setStatus(1);
        record.setTime(180);
        record.setEndTime(LocalDateTime.now());
        record.setRewardType(RewardTypeUscan.Point.getIndex());
        record.setUa(requestHeaders.getUa());
        record.setIpAddress(requestHeaders.getIpAddr());
        record.setImei(requestHeaders.getImei());
        record.setAppStore(requestHeaders.getAppStore());
        record.setOrderId("");
        record.setSdkKey("ZY_CPA");
        record.setRouseDetailId(0);
        record.setIsNewMember(0);
        record.setDownType(0);
        record.setIsOp(0);
        record.setReleaseTime(LocalDateTime.now());
        record.setPushTime(LocalDateTime.now());
        record.setSdkKeyAppStoreIsNew("");
        downloadMemberRecordService.insertModel(record);
        return Callback.success("success", "查询成功", null);
    }


    @Sessionid
    @Require
    @PostMapping("/strategyTip")
    public JsonData strategyTip(String sdkKey) {
        return Callback.success("200", "查询成功", downAppService.selectByKey(sdkKey));
    }

    @Sessionid
    @Require
    @PostMapping("/cleanSecond")
    public JsonData clickStrategyTip(HttpServletRequest request, String sdkKey) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        TaskRouse taskRouse = downAppService.selectByKey(sdkKey);
        if (taskRouse == null) {
            return Callback.success("201", "查询成功", Whether.NO.getDbIndex());
        }
        if (newRouseService.checkShow(requestHeaders.getUserid(), taskRouse)) {
            return Callback.success("201", "查询成功", taskRouse.getCleanZeroSecond());
        }
        return Callback.success("201", "查询成功", Whether.NO.getDbIndex());
    }


    @PostMapping("/open")
    public JsonData open(HttpServletRequest request, long recordId) {
        RequestHeaders header = new RequestHeaders(request);
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("201", "任务不存在");
        }
        if (!record.getMemberId().equals(header.getUserid())) {
            return Callback.fail("202", "任务不存在.");
        }
        record.setIsOpen(Whether.YES.getDbIndex());
        downAppService.updateKey(record);
        return Callback.success("success", "查询成功", null);
    }


}
